package com.summer.utils.Pinyin4j;

import com.jd.jsf.gd.util.StringUtils;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * //fixme 声调不准，多音字处理不是很好
 */
public class Pinyin4jUtil {

    /**
     * 获取汉字串拼音，带声调，英文字符不变
     * @param str 汉字串
     * @return
     */
    public static String toPinyinWithTone(String str) {
        return toPinyin(str, true);
    }

    /**
     * 获取汉字串拼音，不带声调，英文字符不变
     * @param str 汉字串
     * @return
     */
    public static String toPinyin(String str) {
        return toPinyin(str, false);
    }
    /**
     * 获取汉字串拼音，英文字符不变
     * @param str 汉字串
     * @param withTone 是否带声调
     * @return
     */
    public static String toPinyin(String str, boolean withTone) {
        if (StringUtils.isEmpty(str)) {
            return "";
        }
        String output = "";
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        if (!withTone) {
            format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        }
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        char[] input = str.trim().toCharArray();
        try {
            for (int i = 0; i < input.length; i++) {
                if (Character.toString(input[i]).matches("[\\u4E00-\\u9FA5]+")) {
                    String[] temp = PinyinHelper.toHanyuPinyinStringArray(input[i], format);
                    output += temp[0];
                } else {
                    output += Character.toString(input[i]);
                }
            }
        } catch (BadHanyuPinyinOutputFormatCombination e) {
            e.printStackTrace();
            return "";
        }

        return output;
    }

    public static void main(String[] args) {
        System.out.println(toPinyin("郝义涛"));
        System.out.println(toPinyinWithTone("郝义涛"));
    }
}
